package net.monare.mifss.evn;

import com.vaadin.navigator.Navigator;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.UI;
import net.monare.mifss.MifssAdminMainUI;
import net.monare.mifss.MifssMessages;
import net.monare.mifss.admin.ui.LoginForm;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class LoginFormListener implements ClickListener {

    private static final long serialVersionUID = -2910088258271883433L;

    Logger logger = Logger.getLogger(LoginFormListener.class);
    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void buttonClick(ClickEvent event) {

        try {

            Button source = event.getButton();
            LoginForm parent = (LoginForm) source.getParent().getParent().getParent();

            String username = parent.getTxtLogin().getValue();
            String password = parent.getTxtPassword().getValue();

            UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(username, password);

            Authentication result = authenticationManager.authenticate(request);

          SecurityContext securityContext = ((MifssAdminMainUI)UI.getCurrent()).getSecurityContext();

            securityContext.setAuthentication(result);


            MifssAdminMainUI current = (MifssAdminMainUI) UI.getCurrent();

            Navigator navigator = current.getNavigator();
            navigator.navigateTo("admin");

        } catch (AuthenticationException e) {
            logger.error(e, e);
            Notification.show(MifssMessages.getMessage("sys.error.authentication.failed") + " : " + e.getMessage(), Type.TRAY_NOTIFICATION);
        }

    }

}
